package com.haitaoit.chengquan.module.home.adapter.forum;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.view.Img;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

public class ImageAdapter extends BaseAdapter {
    private List<Img> list;
    private Context context;
    private BackCall backCall;

    public ImageAdapter(Context context) {
        this.context = context;
        if (list == null) {
            list = new ArrayList<Img>();
        }
    }

    public List<Img> getList() {
        return list;
    }

    public void setList(List<Img> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        int num;
        if (list.size() < 3) {
            num = list.size() + 1;
        } else {
            num = 3;
        }
        return num;
    }

    @Override
    public Object getItem(int arg0) {
        return list.get(arg0);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.image_item, null);
            ViewUtils.inject(holder, convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        DisplayMetrics metrics = convertView.getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp1 = holder.icon.getLayoutParams();
        lp1.height = (metrics.widthPixels - 55) / 3;
        holder.icon.setLayoutParams(lp1);
        holder.icon.setImageResource(R.mipmap.pic23_2);
        if (list.size() != 0) {
            if (position < list.size()) {
                holder.icon.setImageBitmap(list.get(position).getBmp());
            }
        }
        holder.icon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                backCall.deal(R.id.icon, position);
            }
        });
        return convertView;
    }

    public class ViewHolder {
        @ViewInject(R.id.icon)
        ImageView icon;
    }

    public void setBackCall(BackCall backCall) {
        this.backCall = backCall;
    }

}
